package com.ruoyi.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.web.domain.BhRiskList;
import com.ruoyi.web.domain.BhRiskPost;
import com.ruoyi.web.domain.query.*;
import com.ruoyi.web.domain.vo.BhRiskListPageVO;
import com.ruoyi.web.domain.vo.ReportActivityVO;
import com.ruoyi.web.listener.ExcelAnalysisHelper;
import com.ruoyi.web.mapper.BhRiskListMapper;
import com.ruoyi.web.mapper.BhRiskPostMapper;
import com.ruoyi.web.service.BhRiskListService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.util.*;

@Slf4j
@Service
public class BhRiskListServiceImpl implements BhRiskListService {

    @Autowired
    private BhRiskListMapper bhRiskListMapper;
    @Autowired
    private BhRiskPostMapper bhRiskPostMapper;

    /**
     * 获取全量的风险库数据(作业活动风险)
     *
     * @param tabName 模板类型
     * @return 作业活动风险数据
     */
    @Override
    public R<List<ReportActivityVO>> getAllData(String tabName) {
        List<ReportActivityVO> result = new ArrayList<>();
        List<BhRiskList> bhRiskLists = bhRiskListMapper.getAllData(tabName);
        bhRiskLists.forEach(x -> {
            ReportActivityVO reportActivity = new ReportActivityVO();
            BeanUtils.copyProperties(x, reportActivity);
            result.add(reportActivity);
        });
        return R.ok(result);
    }

    /**
     * 获取风险详情数据
     *
     * @param id 风险库id
     * @return 风险详情
     */
    @Override
    public R<BhRiskList> getReportRiskList(Integer id) {
        return R.ok(bhRiskListMapper.selectById(id));
    }

    /**
     * 导入风险库
     *
     * @param inputStream 文件流
     */
    @Override
    public R<Void> importExcel(InputStream inputStream, String tabName) {
        if ("2".equals(tabName)) {
            return handleRiskPost(inputStream);
        } else if ("1".equals(tabName)) {
            return handleRiskList(inputStream, tabName);
        } else {
            return R.fail("tabName:" + tabName + " 传值错误！");
        }
    }

    // 导入 跟班干部检查模板
    private R<Void> handleRiskPost(InputStream inputStream) {
        ExcelAnalysisHelper<ExcelPostQuery> helper = new ExcelAnalysisHelper();
        // 参数 文件流，sheet页号，头行号
        List<ExcelPostQuery> listData = helper.getList(inputStream, ExcelPostQuery.class, 0, 4);
        if (!CollectionUtils.isEmpty(listData)) {
            Set<String> mainSet = new HashSet<>();
            for (ExcelPostQuery excelPostQuery : listData) {
                mainSet.add(excelPostQuery.getCheckItem().trim());
            }
            if (!CollectionUtils.isEmpty(mainSet)) {
                for (String mainName : mainSet) {
                    BhRiskPost mainPost = bhRiskPostMapper.selectOne(new LambdaQueryWrapper<BhRiskPost>().eq(BhRiskPost::getDelFlag, 0).eq(BhRiskPost::getParentId, 0).eq(BhRiskPost::getName, mainName));
                    if (Objects.isNull(mainPost)) {
                        BhRiskPost addMainParam = new BhRiskPost();
                        addMainParam.setDelFlag(0);
                        addMainParam.setParentId(0);
                        addMainParam.setName(mainName);
                        if (bhRiskPostMapper.insert(addMainParam) <= 0) {
                            return R.fail("添加主数据：" + mainName + "失败！");
                        }
                    }
                }
            }
            Set<BhRiskPost> pointSet = new HashSet<>();
            for (ExcelPostQuery excelPostQuery : listData) {
                BhRiskPost point = new BhRiskPost();
                Integer mainId = bhRiskPostMapper.selectOne(new LambdaQueryWrapper<BhRiskPost>().eq(BhRiskPost::getDelFlag, 0).eq(BhRiskPost::getParentId, 0).eq(BhRiskPost::getName, excelPostQuery.getCheckItem().trim())).getId();
                point.setParentId(mainId);
                point.setName(excelPostQuery.getCheckDetail().trim());
                pointSet.add(point);
            }
            if (!CollectionUtils.isEmpty(pointSet)) {
                for (BhRiskPost point : pointSet) {
                    BhRiskPost pointRisk = bhRiskPostMapper.selectOne(new LambdaQueryWrapper<BhRiskPost>().eq(BhRiskPost::getDelFlag, 0).eq(BhRiskPost::getParentId, point.getParentId()).eq(BhRiskPost::getName, point.getName()));
                    if (Objects.isNull(pointRisk)) {
                        BhRiskPost addPointParam = new BhRiskPost();
                        addPointParam.setParentId(point.getParentId());
                        addPointParam.setName(point.getName());
                        addPointParam.setDelFlag(0);
                        if (bhRiskPostMapper.insert(addPointParam) <= 0) {
                            return R.fail("添加分数据：" + point.getName() + "失败！");
                        }
                    }
                }
            }
        }
        return R.ok();
    }

    // 导入 作业活动检查模板
    @NotNull
    private R<Void> handleRiskList(InputStream inputStream, String tabName) {
        ExcelAnalysisHelper<ExcelRiskQuery> helper = new ExcelAnalysisHelper();
        // 参数 文件流，sheet页号，头行号
        List<ExcelRiskQuery> listData = helper.getList(inputStream, ExcelRiskQuery.class, 0, 3);
        if (!CollectionUtils.isEmpty(listData)) {
            Set<String> mainSet = new HashSet<>();
            for (ExcelRiskQuery data : listData) {
                if (StringUtils.isBlank(data.getMainName())) {
                    return R.fail("有主单元未合并");
                }
                mainSet.add(data.getMainName().trim());
            }
            if (!CollectionUtils.isEmpty(mainSet)) {
                for (String mainName : mainSet) {
                    BhRiskList mainRisk = bhRiskListMapper.selectOne(new LambdaQueryWrapper<BhRiskList>().eq(BhRiskList::getDelFlag, 0).eq(BhRiskList::getParentId, 0).eq(BhRiskList::getName, mainName));
                    if (Objects.isNull(mainRisk)) {
                        BhRiskList addMainParam = new BhRiskList();
                        buildAddParam(addMainParam, tabName, mainName, 0);
                        if (bhRiskListMapper.insert(addMainParam) <= 0) {
                            return R.fail("添加主单元：" + mainName + "失败！");
                        }
                    }
                }
            }
            log.info("导入-主单元处理结束！");
            Set<BhRiskList> pointSet = new HashSet<>();
            for (ExcelRiskQuery data : listData) {
                BhRiskList point = new BhRiskList();
                if (StringUtils.isBlank(data.getPointName())) {
                    return R.fail("有分单元未合并");
                }
                Integer mainId = bhRiskListMapper.selectOne(new LambdaQueryWrapper<BhRiskList>().eq(BhRiskList::getDelFlag, 0).eq(BhRiskList::getParentId, 0).eq(BhRiskList::getName, data.getMainName().trim())).getId();
                point.setParentId(mainId);
                point.setName(data.getPointName().trim());
                pointSet.add(point);
            }
            if (!CollectionUtils.isEmpty(pointSet)) {
                for (BhRiskList point : pointSet) {
                    BhRiskList pointRisk = bhRiskListMapper.selectByParam(point);
                    if (Objects.isNull(pointRisk)) {
                        BhRiskList addPointParam = new BhRiskList();
                        buildAddParam(addPointParam, tabName, point.getName(), point.getParentId());
                        if (bhRiskListMapper.insert(addPointParam) <= 0) {
                            return R.fail("添加分单元：" + point.getName() + "失败！");
                        }
                    }
                }
            }
            log.info("导入-分单元处理结束！");
            for (ExcelRiskQuery data : listData) {
                BhRiskList getActivityParam = new BhRiskList();
                Integer mainId = bhRiskListMapper.selectOne(new LambdaQueryWrapper<BhRiskList>().eq(BhRiskList::getDelFlag, 0).eq(BhRiskList::getParentId, 0).eq(BhRiskList::getName, data.getMainName().trim())).getId();
                Integer pointId = bhRiskListMapper.selectOne(new LambdaQueryWrapper<BhRiskList>().eq(BhRiskList::getDelFlag, 0).eq(BhRiskList::getName, data.getPointName().trim()).eq(BhRiskList::getParentId, mainId)).getId();
                getActivityParam.setParentId(pointId);
                getActivityParam.setName(data.getActivityName());
                BhRiskList activity = bhRiskListMapper.selectByParam(getActivityParam);
                if (Objects.isNull(activity)) {
                    BhRiskList addActivity = new BhRiskList();
                    buildAddParam(addActivity, tabName, data.getActivityName(), pointId);
                    BeanUtils.copyProperties(data, addActivity);
                    if (bhRiskListMapper.insert(addActivity) <= 0) {
                        return R.fail("添加：" + addActivity.getName() + "失败！");
                    }
                } else {
                    BhRiskList modActivity = new BhRiskList();
                    BeanUtils.copyProperties(data, modActivity);
                    modActivity.setId(activity.getId());
                    if (bhRiskListMapper.updateById(modActivity) <= 0) {
                        return R.fail("修改：" + activity.getName() + "失败！");
                    }
                }
            }
            log.info("导入-处理完成！");
        }
        return R.ok();
    }

    /**
     * 新增风险库数据
     *
     * @param addRiskListQuery 新增数据
     * @return 返回
     */
    @Transactional
    @Override
    public R<Void> addRiskList(AddRiskListQuery addRiskListQuery) {
        String tabName = addRiskListQuery.getTabName();
        if ("2".equals(tabName)) {
            // 新增跟班干部检查数据
            return insertRiskPost(addRiskListQuery);
        } else if ("1".equals(tabName)) {
            // 新增作业活动检查数据
            return insertRiskList(addRiskListQuery, tabName);
        } else {
            return R.fail("tabName:" + tabName + " 传值错误！");
        }
    }

    private R<Void> insertRiskPost(AddRiskListQuery addRiskListQuery) {
        String mainName = addRiskListQuery.getMainName().trim();
        // 处理第一级
        Integer parentId = 0;
        BhRiskPost first = bhRiskPostMapper.selectOne(new LambdaQueryWrapper<BhRiskPost>().eq(BhRiskPost::getDelFlag, 0).eq(BhRiskPost::getParentId, parentId).eq(BhRiskPost::getName, mainName));
        if (ObjectUtils.isNotEmpty(first)) {
            parentId = first.getId();
        } else {
            BhRiskPost addParam = new BhRiskPost();
            addParam.setDelFlag(0);
            addParam.setParentId(parentId);
            addParam.setName(mainName);
            bhRiskPostMapper.insert(addParam);
            parentId = addParam.getId();
        }
        // 处理第二级
        List<Points> points = addRiskListQuery.getPoints();
        if (!CollectionUtils.isEmpty(points)) {
            for (Points point : points) {
                String pointName = point.getPointName();
                if (StringUtils.isNotBlank(pointName)) {
                    BhRiskPost second = bhRiskPostMapper.selectOne(new LambdaQueryWrapper<BhRiskPost>().eq(BhRiskPost::getDelFlag, 0).eq(BhRiskPost::getParentId, parentId).eq(BhRiskPost::getName, pointName));
                    if (ObjectUtils.isEmpty(second)) {
                        BhRiskPost addParam = new BhRiskPost();
                        addParam.setDelFlag(0);
                        addParam.setParentId(parentId);
                        addParam.setName(pointName);
                        bhRiskPostMapper.insert(addParam);
                    }
                }
            }
        }
        return R.ok();
    }

    private R<Void> insertRiskList(AddRiskListQuery addRiskListQuery, String tabName) {
        BhRiskList getParam = new BhRiskList();
        String mainName = addRiskListQuery.getMainName().trim();
        getParam.setTabName(tabName);
        getParam.setName(mainName);
        getParam.setParentId(0);
        // 处理第一级
        BhRiskList first = bhRiskListMapper.selectByParam(getParam);
        Integer parentId = 0;
        if (ObjectUtils.isNotEmpty(first)) {
            parentId = first.getId();
        } else {
            BhRiskList addParam = new BhRiskList();
            buildAddParam(addParam, tabName, mainName, parentId);
            bhRiskListMapper.insert(addParam);
            parentId = addParam.getId();
        }
        // 处理第二级
        List<Points> points = addRiskListQuery.getPoints();
        if (!CollectionUtils.isEmpty(points)) {
            for (Points point : points) {
                handleSecond(getParam, tabName, parentId, point);
            }
        }
        return R.ok();
    }

    private Integer handleSecond(BhRiskList getParam, String tabName, Integer parentId, Points point) {
        String pointName = point.getPointName();
        Integer pointId;
        if (StringUtils.isNotBlank(pointName)) {
            getParam.setName(pointName);
            getParam.setParentId(parentId);
            BhRiskList second = bhRiskListMapper.selectByParam(getParam);
            if (ObjectUtils.isNotEmpty(second)) {
                pointId = second.getId();
            } else {
                BhRiskList addParam = new BhRiskList();
                buildAddParam(addParam, tabName, pointName, parentId);
                bhRiskListMapper.insert(addParam);
                pointId = addParam.getId();
            }
            // 处理三级
            List<Activities> activities = point.getActivities();
            if (!CollectionUtils.isEmpty(activities)) {
                for (Activities activity : activities) {
                    String activityName = activity.getActivityName();
                    if (StringUtils.isNotBlank(activityName)) {
                        BhRiskList addParam = new BhRiskList();
                        buildAddParam(addParam, tabName, activity.getActivityName(), pointId);
                        BeanUtils.copyProperties(activity, addParam);
                        bhRiskListMapper.insert(addParam);
                    }
                }
            }
        }
        return parentId;
    }

    private void buildAddParam(BhRiskList addParam, String tabName, String name, Integer parentId) {
        addParam.setTabName(tabName);
        addParam.setName(name);
        addParam.setDelFlag(0);
        addParam.setStatus("0");
        addParam.setCreateTime(new Date());
        addParam.setParentId(parentId);
    }

    /**
     * 编辑风险库
     *
     * @param addRiskListQuery 编辑参数
     * @return 返回
     */
    @Override
    public R<Void> modRiskList(AddRiskListQuery addRiskListQuery) {
        String tabName = addRiskListQuery.getTabName();
        if ("2".equals(tabName)) {
            return upRiskPost(addRiskListQuery);
        } else if ("1".equals(tabName)) {
            return upRiskList(addRiskListQuery, tabName);
        } else {
            return R.fail("tabName:" + tabName + " 传值错误！");
        }
    }

    private R<Void> upRiskPost(AddRiskListQuery addRiskListQuery) {
        BhRiskPost main = bhRiskPostMapper.selectById(addRiskListQuery.getId());
        if (Objects.isNull(main)) {
            return R.fail("主数据id错误！");
        }
        if (!main.getName().equals(addRiskListQuery.getMainName())) {
            BhRiskPost modParam = new BhRiskPost();
            modParam.setId(addRiskListQuery.getId());
            modParam.setName(addRiskListQuery.getMainName());
            if (bhRiskPostMapper.updateById(modParam) <= 0) {
                return R.fail("主数据修改失败！");
            }
        }
        // 处理分数据
        List<Points> points = addRiskListQuery.getPoints();
        if (!CollectionUtils.isEmpty(points)) {
            for (Points point : points) {
                Integer id = point.getId();
                if (id == null) {
                    BhRiskPost addPointParam = new BhRiskPost();
                    addPointParam.setParentId(addRiskListQuery.getId());
                    addPointParam.setName(point.getPointName());
                    addPointParam.setDelFlag(0);
                    bhRiskPostMapper.insert(addPointParam);
                } else {
                    BhRiskPost getPointParam = new BhRiskPost();
                    getPointParam.setParentId(addRiskListQuery.getId());
                    getPointParam.setId(id);
                    BhRiskPost pointRisk = bhRiskPostMapper.selectOne(new LambdaQueryWrapper<BhRiskPost>().eq(BhRiskPost::getDelFlag, 0).eq(BhRiskPost::getParentId, getPointParam.getParentId()).eq(BhRiskPost::getId, getPointParam.getId()));
                    if (Objects.isNull(pointRisk)) {
                        return R.fail("分数据id:" + id + " 错误！");
                    }
                    if (!pointRisk.getName().equals(point.getPointName())) {
                        BhRiskPost modParam = new BhRiskPost();
                        modParam.setId(id);
                        modParam.setName(point.getPointName());
                        if (bhRiskPostMapper.updateById(modParam) <= 0) {
                            return R.fail("分数据id:" + id + " 修改失败！");
                        }
                    }
                }
            }
        }
        return R.ok();
    }

    @NotNull
    private R<Void> upRiskList(AddRiskListQuery addRiskListQuery, String tabName) {
        BhRiskList getParam = new BhRiskList();
        getParam.setTabName(tabName);
        getParam.setId(addRiskListQuery.getId());
        BhRiskList main = bhRiskListMapper.selectByParam(getParam);
        if (Objects.isNull(main)) {
            return R.fail("主单元id错误！");
        }
        if (!main.getName().equals(addRiskListQuery.getMainName())) {
            BhRiskList modParam = new BhRiskList();
            modParam.setId(addRiskListQuery.getId());
            modParam.setName(addRiskListQuery.getMainName());
            if (bhRiskListMapper.updateById(modParam) <= 0) {
                return R.fail("主单元修改失败！");
            }
        }
        // 处理分单元
        List<Points> points = addRiskListQuery.getPoints();
        if (!CollectionUtils.isEmpty(points)) {
            for (Points point : points) {
                List<Activities> activities = point.getActivities();
                Integer id = point.getId();
                if (id == null) {
                    BhRiskList addParam = new BhRiskList();
                    buildAddParam(addParam, tabName, point.getPointName(), addRiskListQuery.getId());
                    bhRiskListMapper.insert(addParam);
                } else {
                    BhRiskList getPointParam = new BhRiskList();
                    getPointParam.setParentId(addRiskListQuery.getId());
                    getPointParam.setId(id);
                    getPointParam.setTabName(addRiskListQuery.getTabName());
                    BhRiskList pointRisk = bhRiskListMapper.selectByParam(getPointParam);
                    if (Objects.isNull(pointRisk)) {
                        return R.fail("分单元id:" + id + " 错误！");
                    }
                    if (!pointRisk.getName().equals(point.getPointName())) {
                        BhRiskList modParam = new BhRiskList();
                        modParam.setId(id);
                        modParam.setName(point.getPointName());
                        if (bhRiskListMapper.updateById(modParam) <= 0) {
                            return R.fail("分单元id:" + id + " 修改失败！");
                        }
                    }
                    // 处理三级
                    if (!CollectionUtils.isEmpty(activities)) {
                        for (Activities activity : activities) {
                            Integer activityId = activity.getId();
                            if (activityId == null) {
                                BhRiskList addParam = new BhRiskList();
                                BeanUtils.copyProperties(activity, addParam);
                                buildAddParam(addParam, tabName, activity.getActivityName(), id);
                                bhRiskListMapper.insert(addParam);
                            } else {
                                BhRiskList getActivityParam = new BhRiskList();
                                getActivityParam.setParentId(id);
                                getActivityParam.setId(activityId);
                                getActivityParam.setTabName(addRiskListQuery.getTabName());
                                BhRiskList activityRisk = bhRiskListMapper.selectByParam(getActivityParam);
                                if (Objects.isNull(activityRisk)) {
                                    return R.fail("活动步骤id:" + id + " 错误！");
                                }
                                BhRiskList modActivityParam = new BhRiskList();
                                BeanUtils.copyProperties(activity, modActivityParam);
                                if (bhRiskListMapper.updateById(modActivityParam) <= 0) {
                                    return R.fail("活动步骤id:" + id + " 修改失败！");
                                }
                            }
                        }
                    }
                }
            }
        }
        return R.ok();
    }

    /**
     * 删除
     *
     * @param query 删除
     * @return 返回
     */
    @Override
    public R<Void> delRiskById(AddRiskListQuery query) {
        String tabName = query.getTabName();
        if ("2".equals(tabName)) {
            return delPost(query);
        } else if ("1".equals(tabName)) {
            return delRisk(query);
        } else {
            return R.fail("tabName:" + tabName + " 传值错误！");
        }
    }

    private R<Void> delPost(AddRiskListQuery query) {
        bhRiskPostMapper.deleteById(query.getId());
        return R.ok();
    }

    @NotNull
    private R<Void> delRisk(AddRiskListQuery query) {
        BhRiskList riskInfo = bhRiskListMapper.selectById(query.getId());
        bhRiskListMapper.deleteById(query.getId());
        /**
         * 判断分单元是否要删除
         */
        BhRiskList fenDanYuan = bhRiskListMapper.selectById(riskInfo.getParentId());
        Long fenCount = bhRiskListMapper.selectCount(new LambdaQueryWrapper<BhRiskList>()
            .eq(BhRiskList::getParentId, fenDanYuan.getId()).eq(BhRiskList::getDelFlag, 0));
        if (0L == fenCount) {
            bhRiskListMapper.deleteById(fenDanYuan.getId());
        }
        /**
         * 判断主单元是否要删除
         */
        BhRiskList mainYuan = bhRiskListMapper.selectById(fenDanYuan.getParentId());
        Long mainCount = bhRiskListMapper.selectCount(
            new LambdaQueryWrapper<BhRiskList>()
                .eq(BhRiskList::getParentId, mainYuan.getId())
                .eq(BhRiskList::getDelFlag, 0));
        if (0L == mainCount) {
            bhRiskListMapper.deleteById(mainYuan.getId());
        }

        return R.ok();
    }

    /**
     * 分页查询风险库数据
     *
     * @param riskPageQuery 查询条件
     * @return 风险库数据
     */
    @Override
    public TableDataInfo<BhRiskListPageVO> getRiskListPage(RiskPageQuery riskPageQuery) {
        if (riskPageQuery.getId1() != null) {
            BhRiskList info = bhRiskListMapper.selectById(riskPageQuery.getId1());
            riskPageQuery.setId1Str(info != null ? info.getName() : null);
        }
        if (riskPageQuery.getId2() != null) {
            BhRiskList info = bhRiskListMapper.selectById(riskPageQuery.getId2());
            riskPageQuery.setId2Str(info != null ? info.getName() : null);
        }
        if (riskPageQuery.getId3() != null) {
            BhRiskList info = bhRiskListMapper.selectById(riskPageQuery.getId3());
            riskPageQuery.setId3Str(info != null ? info.getName() : null);
        }
        List<BhRiskList> list = bhRiskListMapper.getRiskListPage(riskPageQuery);
        TableDataInfo<BhRiskListPageVO> result = TableDataInfo.build();
        result.setTotal(list.size());
        if (riskPageQuery.getPageNum() == null) {
            riskPageQuery.setPageNum(1);
        }
        // 添加 主单元
        if (!CollectionUtils.isEmpty(list)) {
            BhRiskList topInfo = list.get(riskPageQuery.getPageNum() - 1);
            if (topInfo != null) {
                riskPageQuery.setId1(topInfo.getId());
                List<BhRiskList> bhRiskLists = bhRiskListMapper.selectVoListByPid(riskPageQuery);
                List<BhRiskListPageVO> resultList = new ArrayList<>();
                if (!CollectionUtils.isEmpty(bhRiskLists)) {
                    for (BhRiskList bhRiskList : bhRiskLists) {
                        BhRiskListPageVO bhRiskListPage = new BhRiskListPageVO();
                        BeanUtils.copyProperties(bhRiskList, bhRiskListPage);
                        resultList.add(bhRiskListPage);
                    }
                }
                result.setData(resultList);
            }
        }
        return result;
    }
}
